import axios from 'axios';
import { message } from 'antd';

export default function ajax(
  url,
  data = {},
  method = 'GET',
  type = 'urlencoded'
) {
  //axios.defaults.baseURL = 'http://159.75.128.32:5000';

  var header = '';
  switch (type) {
    case 'json':
      header = 'application/json';
      break;
    case 'x-www-form-urlencoded':
      header = 'application/x-www-form-urlencoded';
      break;
    case 'form-data':
      header = 'multipart/form-data';
      break;
    default:
      header = 'application/x-www-form-urlencoded';
      break;
  }

  return new Promise((resolve, reject) => {
    let promise;
    switch (method) {
      case 'GET':
        promise = axios.get(url, {
          params: data,
          headers: {},
        });
        break;
      case 'POST':
        promise = axios.post(url, data, {
          params: {},
          header,
        });
        break;
      case 'PUT':
        promise = axios.put(url, data, {
          params: {},
          header,
        });
        break;
      default:
        promise = axios.post(url, data, {
          params: {},
          header,
        });
    }

    promise
      .then((response) => {
        resolve(response.data);
      })
      .catch((err) => {
        reject(err);
        message.error(err.message);
      });
  });
}
